#include "sprite_fx.h"

#include "util/timer.h"				// log
#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    

using namespace vfx;

SpriteSFX::SpriteSFX(EffectMan*	pParent, const std::string& Image, int	MaxCount, bool Floating , bool Additive) :
	SFXSet(pParent),
	m_MaxCount(0),
	m_CurrentCount(0),
	m_SpriteA(NULL),
	m_Floating(Floating),
	m_Additive(Additive)
{
	m_MaxCount = MaxCount;
	m_SpriteA = new SimpleSprite[m_MaxCount];
	for (int i=0; i<MaxCount; i++)
	{
		m_SpriteA[i].Sprite.Create(Image);
		m_SpriteA[i].Active = false;
		m_SpriteA[i].Sprite.m_Additive = m_Additive;
	}
	if (MaxCount > 0)
	{
		m_SpriteA[0].Sprite.GetScreenSize(m_Size);
	}
}

SpriteSFX::~SpriteSFX()
{
	UTIL_SAFE_DELETEA(m_SpriteA);
}

void					SpriteSFX::Render(const math::Vec2& Offset, float Scale)
{
	if (m_CurrentCount <=0) return;
	for (int i=0; i<m_MaxCount; i++)
	{
		SimpleSprite* pSprite = &m_SpriteA[i];
		if (pSprite->Active)	
		{
			pSprite->Sprite.m_Pos = (pSprite->Pos - Offset) * Scale;
			pSprite->Sprite.m_Size = m_Size * Scale;
			pSprite->Sprite.Render();
		}
	}
}

void					SpriteSFX::Tick(float dt)
{
	if (m_CurrentCount <=0) return;
	const math::Vec2	FloatSpeed(0, 0.5f);
	for (int i=0; i<m_MaxCount; i++)
	{
		if (m_SpriteA[i].Active)	
		{
			bool SeqEnd = m_SpriteA[i].Sprite.Tick(dt);
			if (!SeqEnd)
			{
				m_SpriteA[i].Active = false;
				m_CurrentCount--;
			}
			if (m_Floating)
			{
				m_SpriteA[i].Pos+=FloatSpeed * dt;
			}
		}
	}
}

void					SpriteSFX::AddSprite(const math::Vec2& Pos,  bool IsFlipped,COLOR Color)
{
	math::Vec2	Size;
	m_SpriteA[0].Sprite.GetScreenSize(Size);
	AddSprite(Pos, Size, IsFlipped, Color);
}


void					SpriteSFX::AddCentered(const math::Vec2& Pos, bool IsFlipped, COLOR Color)
{
	math::Vec2	Size;
	m_SpriteA[0].Sprite.GetScreenSize(Size);
	AddSprite(Pos - (Size*0.5f), Size, IsFlipped, Color);
}


void					SpriteSFX::AddSprite(const math::Vec2& Pos, const math::Vec2& Size,  bool IsFlipped,COLOR Color)
{
	if (m_CurrentCount == m_MaxCount) return;	// cannot

	for (int i=0; i<m_MaxCount; i++)
	{
		if (!m_SpriteA[i].Active)
		{
			m_SpriteA[i].Active = true;
			m_SpriteA[i].Pos = Pos;
			m_SpriteA[i].Size = Size;
			m_SpriteA[i].Color = Color;
			m_SpriteA[i].Sprite.Setup(Pos, Size, 0, 1, Color);
			m_SpriteA[i].Sprite.m_IsFlipped = IsFlipped;
			m_CurrentCount++;
			return;
		}
	}
}

void					SpriteSFX::GetSpriteSize(math::Vec2& Size)
{
	m_SpriteA[0].Sprite.GetScreenSize(Size);
}
